package com.lixinxin.commoncomposeproject.screen

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Button
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.PermissionRequired
import com.google.accompanist.permissions.rememberPermissionState as rememberPermissionState1

/**
 *   author ： lixinxin
 *   time    ： 2021-12-01
 *   email：895330766@qq.com
 *
 *
 */
@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun PermissionsScreen() {

    val context= LocalContext.current

    Surface() {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.Red)
        ) {
            RequestPermissionUsingAccompanist(context)
        }
    }
}

private fun oCamera(context: Context) {
    Toast.makeText(context, "开始拍照", Toast.LENGTH_SHORT).show()
}


@OptIn(ExperimentalPermissionsApi::class)
@Composable
private fun RequestPermissionUsingAccompanist(context: Context) {

    val permission = Manifest.permission.CAMERA
    // 定义 Permission State
    val permissionState = rememberPermissionState1(permission)
    PermissionRequired(permissionState = permissionState, permissionNotAvailableContent = {
        // 权限获取失败
        Text("Permission Denied.")
    }, permissionNotGrantedContent = {
        // 尚未获取权限时
        Button(onClick = { permissionState.launchPermissionRequest() }) {
            Text("拍照")
        }
    }, content = {
        Button(onClick = { oCamera(context = context) }) {
            Text("拍照")
        }
        // 权限获取成功
    })
}

//普通方式请求权限
@Composable
private fun RequestPermission() {
    // 基于 LocalComposition 获取 Context
    val context = LocalContext.current

    // 基于 LocalLifecycleOwner 获取 Lifecycle
    val lifecycle = LocalLifecycleOwner.current.lifecycle

    // 定义需要动态获取的 Permission 类型
    val permission = Manifest.permission.CAMERA

    // Result API 调用时的 launcher
    val launcher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestPermission(),
        onResult = { isGranted ->
            //判断权限申请结果，并根据结果侠士不同画面，
            // 由于 onResult 不是一个 @Composable lambda，
            // 所以不能直接显示 Composalbe 需要通过修改 state 等方式间接显示 Composable
        }
    )

    // 在 Activity onStart 时，发起权限事情，如果权限已经获得则跳过
    val lifecycleObserver = remember {
        LifecycleEventObserver { _, event ->
            if (event == Lifecycle.Event.ON_START) {
                if (!permission.isGrantedPermission(context)) {
                    launcher.launch(permission)
                }
            }
        }
    }

    // 当 Lifecycle 或者 LifecycleObserver 变化时注册回调，注意 onDispose 中的注销处理避免泄露
    DisposableEffect(lifecycle, lifecycleObserver) {
        lifecycle.addObserver(lifecycleObserver)
        onDispose {
            lifecycle.removeObserver(lifecycleObserver)
        }
    }
}

private fun String.isGrantedPermission(context: Context): Boolean {
    // 判断是否已经后的状态
    return context.checkSelfPermission(this) == PackageManager.PERMISSION_GRANTED
}